<?php
namespace app\shop\controller;
use app\AdminRest;
use app\farm\model\Farmer;
use app\farm\model\LandCate;
use app\farm\model\ShopGoods;
use app\member\model\DiscountGoods;
use app\shop\model\FreightTemplate;
use app\shop\model\GoodsSpePrice;
use app\shop\model\ShopGoodsCate;
use app\shop\model\ShopGoodsSpe;
use think\App;
use app\shop\model\Goods as Model;
use think\facade\Db;


class AdminGoods extends AdminRest
{


    protected $model;

    protected $cate_model;

    protected $spe_model;

    protected $spe_price_model;


    public function __construct(App $app) {

        parent::__construct($app);

        $this->model = new ShopGoods();

        $this->cate_model = new ShopGoodsCate();

        $this->spe_model = new ShopGoodsSpe();

        $this->spe_price_model = new GoodsSpePrice();

    }






    /**
     * @author chenniang
     * @DataTime: 2021-10-21 11:01
     * @功能说明:商品分类列表
     */
    public function goodsCateList(){

        $input = $this->_param;

        $dis[] = ['uniacid','=',$this->_uniacid];

        $dis[] = ['status','>',-1];

        if(!empty($input['title'])){

            $dis[] = ['title','like','%'.$input['title'].'%'];
        }

        $data = $this->cate_model->dataList($dis,$input['limit']);

        if(!empty($data['data'])){

            $farmer_model = new Farmer();

            foreach ($data['data'] as &$v){

                $v['farmer_name'] = $farmer_model->where('id','in',$v['store'])->column('title');

                $v['farmer_name'] = implode(',',$v['farmer_name']);

            }

        }

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-10-21 11:17
     * @功能说明:添加分类
     */
    public function goodsCateAdd(){

        $input = $this->_input;

        $input['uniacid'] = $this->_uniacid;

        $data = $this->cate_model->dataAdd($input);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-10-21 11:18
     * @功能说明:编辑分类
     */
    public function goodsCateUpdate(){

        $input = $this->_input;

        $input['uniacid'] = $this->_uniacid;

        $dis = [

            'id' => $input['id']

        ];

        $data = $this->cate_model->dataUpdate($dis,$input);

        return $this->success($data);

    }



    /**
     * @author chenniang
     * @DataTime: 2021-10-21 11:18
     * @功能说明:编辑分类
     */
    public function goodsCateInfo(){

        $input = $this->_param;

        $input['uniacid'] = $this->_uniacid;

        $dis = [

            'id' => $input['id']

        ];

        $data = $this->cate_model->dataInfo($dis);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-10-21 17:58
     * @功能说明:分类下拉框
     */
    public function goodsCateSelect(){

        $input['uniacid'] = $this->_uniacid;

        $dis = [

            'uniacid' => $this->_uniacid,

            'status'  => 1

        ];

        $data = $this->cate_model->where($dis)->select()->toArray();

        return $this->success($data);


    }


    /**
     * @author chenniang
     * @DataTime: 2022-07-13 17:21
     * @功能说明:商品列表
     */
    public function goodsList(){

        $input= $this->_param;

        $dis[]= ['a.uniacid','=',$this->_uniacid];

        if(!empty($input['name'])){

            $dis[] = ['a.goods_name','like',"%".$input['name']."%"];
        }

        if(!empty($input['cate_id'])){

            $dis[] = ['c.cate_id','=',$input['cate_id']];
        }

        if(!empty($input['store_id'])){

            $dis[] = ['b.store_id','=',$input['store_id']];
        }

        $sale_type      = $input['type']==2?0:1;

        $sale_out_goods = $this->spe_price_model->getSellOut($this->_uniacid,$sale_type);

        switch ($input['type']){

            case 1:
                $dis[] = ['a.status','=',1];
                break;

            case 2:
                $dis[]= ['a.status','>',-1];
                break;

            case 3:
                $dis[] = ['a.status','=',0];

                break;
        }

        $dis[] = ['a.id','in',$sale_out_goods];

        $data = $this->model->goodsList($dis,$this->_input['limit']);

        $farmer_model = new Farmer();

        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){

                $cate_name = $this->cate_model->where('id','in',$v['cate_id'])->column('title');

                $v['cate_name'] = implode(',',$cate_name);

                $store_name = $farmer_model->where('id','in',$v['store'])->column('title');

                $v['store_name'] = implode(',',$store_name);

            }

        }
        //销售中
        $data['sale_ing'] = $this->model->saleIngCount($this->_uniacid);
        //售罄
        $data['sale_out'] = $this->model->saleIngCount($this->_uniacid,2);
        //下架
        $data['sale_end'] = $this->model->saleIngCount($this->_uniacid,3);

        return $this->success($data);
    }


    /**
     * @author chenniang
     * @DataTime: 2021-10-21 11:33
     * @功能说明:添加商品
     */
    public function goodsAdd(){

        $input = $this->_input;

        $input['uniacid'] = $this->_uniacid;

        Db::startTrans();

        $goods_id = $this->model->dataAdd($input);

        $spe_arr  = $this->goodsSpeAdd($input['specsItem'],$goods_id);

        $res      = $this->goodsSpePriceAdd($input['specsTable'],$goods_id,$spe_arr);

        Db::commit();

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-07-13 17:50
     * @功能说明:修改商品
     */
    public function goodsUpdate(){

        $input= $this->_input;

        $dis  = is_array($input['id'])? ['id','in',$input['id']]:['id' =>$input['id']];

        Db::startTrans();

        $input['uniacid'] = $this->_uniacid;

        $this->model->goodsUpdate($dis,$input);

        $this->spe_model->goodsSpeUpdate(['uniacid'=>$this->_uniacid,'goods_id'=>$input['id']],['status'=>-1]);

        $this->spe_price_model->goodsSpePriceUpdate(['uniacid'=>$this->_uniacid,'goods_id'=>$input['id']],['status'=>-1]);

        $spe_arr = $this->goodsSpeAdd($input['specsItem'],$input['id']);

        $res     = $this->goodsSpePriceAdd($input['specsTable'],$input['id'],$spe_arr);

        Db::commit();

        return $this->success($res);
    }



    /**
     * @author chenniang
     * @DataTime: 2022-08-09 17:49
     * @功能说明:商品复制
     */
    public function goodsCopy(){

        $input = $this->_input;

        $data = $this->model->dataInfo(['id'=>$input['id']]);

        $data['goods_name'] = $input['goods_name'];

        $data['store']      = $input['store'];

        unset($data['id']);

        unset($data['show_price']);

        unset($data['show_init_price']);

        unset($data['all_stock']);

        unset($data['all_sale_count']);

        $spe_info = $this->goodsSpeList($input['id']);

        $data['specsItem'] = $spe_info['text'];

        $data['specsTable'] = $spe_info['price'];

        Db::startTrans();


        $goods_id = $this->model->dataAdd($data);

        $spe_arr  = $this->goodsSpeAdd($data['specsItem'],$goods_id,1);

        $res      = $this->goodsSpePriceAdd($data['specsTable'],$goods_id,$spe_arr);

        Db::commit();

        return $this->success($res);


    }




    /**
     * @author chenniang
     * @DataTime: 2021-10-21 11:21
     * @功能说明:分类详情
     */
    public function goodsInfo(){

        $input = $this->_param;

        $dis = [

            'id' => $input['id']

        ];

        $res['goods_info'] = $this->model->dataInfo($dis);

        $res['spe_info']   = $this->goodsSpeList($input['id']);

        $freightTemplate_model = new FreightTemplate();

        $res['goods_info']['send_template_type'] = $freightTemplate_model->where(['id'=>$res['goods_info']['send_tmpl_id']])->value('type');

        return $this->success($res);

    }

    /**
     * 获取商品规格
     */
    public function goodsSpeList($goods_id){

        $dis['goods_id'] = $goods_id;

        $dis['status']   = 1;

        $data['text']    = $this->spe_model->goodsSpe($dis);

        $data['price']   = $this->spe_price_model->goodsSpePrice($dis);

        if(!empty($data['price'])){

            foreach ($data['price'] as &$v){

                $v['title'] = $v['spe_name_text'];

                $v['true_id'] = $v['id'];

                $v['id']   = implode(',',$v['spe_array_text']);

            }
        }
        return $data;
    }


    /**
     * @author chenniang
     * @DataTime: 2020-08-26 10:09
     * @功能说明:列表页修改商品库存
     */
    public function updateSpe(){

        $input= $this->_input;

        $input= $input['stock'];

        if(!empty($input)&&!is_array($input)){

            $this->errorMsg('数据错误');
        }

        foreach ($input as $value){

            $this->spe_price_model->goodsSpePriceUpdate(['id'=>$value['id']],['stock'=>$value['stock']]);
        }

        return $this->success(true);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-10-28 10:33
     * @功能说明:修改商品基本的参数
     */
    public function goodsBasicUpdate(){

        $input= $this->_input;

        $dis = [

            'id' => $input['id']
        ];

        $res = $this->model->goodsUpdate($dis,$input);

        return $this->success($res);

    }


    /**
     * 上下架删除商品
     */
    public function goodsStatusUpdate(){

        $input= $this->_input;

        if(isset($input['status'])){

            $data = ['status'=>$input['status']];

        }else{

            $data = ['index_show'=>$input['index_show']];

        }
        $res = $this->model->where('id','in',$input['id'])->update($data);

        return $this->success($res);
    }


    /**
     * @param $data
     * @param $goods_id
     * @return array
     * 添加多规格
     */
    public function goodsSpeAdd($data,$goods_id,$is_copy=0){
        /**
         * 循环判断是否存在多个规格名添加图片的问题
         * @date 2020/5/14 10:42 --lichuanming
         */
        $isimg_count = 0;
        foreach ($data as $item ){
            if($item['is_img'] == 1){
                $isimg_count++;
            }
        }
        if($isimg_count > 1){
            return $this->error('当前已有规格名添加了图片，继续添加则需取消上一个规格名的图片勾选');
        }

        $arr = array();
        if(!empty($data)){
            foreach ($data as $v){
                $is_img = $v['is_img']?$v['is_img']:0; #@date 2020/5/14 10:42 --lichuanming
                if(strlen($v['pid'])>10||$is_copy==1){
                    $pid =  $this->spe_model->goodsSpeAdd(['uniacid'=>$this->_uniacid,'goods_id'=>$goods_id,'title'=>$v['title'],'is_img'=>$is_img]);
                }else{
                    $this->spe_model->goodsSpeUpdate(['id'=>$v['id']],['status'=>1,'title'=>$v['title'],'is_img'=>$is_img]);
                    $pid = $v['id'];
                }
                if(!empty($v['cate'])){
                    foreach ($v['cate'] as $value){
                        $image = $is_img?$value['image']:''; #@date 2020/5/14 10:42 --lichuanming

                        if(strlen($value['id'])>10||$is_copy==1) {
                            $id = $this->spe_model->goodsSpeAdd(['uniacid' => $this->_uniacid, 'goods_id' => $goods_id, 'title' => $value['title'], 'pid' => $pid,'is_img'=>$is_img,'image'=>$image]);
                        }else{
                            $this->spe_model->goodsSpeUpdate(['id'=>$value['id']],['status'=>1,'title'=>$value['title'],'is_img'=>$is_img,'image'=>$image]);
                            $id = $value['id'];
                        }
                        $arr[$value['id']] = $id;
                    }
                }
            }
        }

       // dump($data,$arr);exit;
        return $arr;
    }


    /**
     * @param $data
     * @param $good_id
     * @param $arr
     * @return int|string
     * 添加多规格价格
     */
    public function goodsSpePriceAdd($data,$good_id,$arr){
        if(!empty($data)){
            foreach ($data as $v){
                if (strlen($v['price'])>8||strlen($v['original_price'])>8){

                   // $this->errorMsg('价格最多8位');

                }

                $pid    = explode(',',$v['id']);
                $spe_id = [];
                if(empty($arr)){
                    $this->errorMsg('规格不正确,请删除错误规格，重新编辑');
                }
                foreach ($pid as $value){
                    if(!key_exists($value,$arr)){
                        $this->errorMsg('规格不正确,请删除错误规格，重新编辑');
                    }
                    $spe_id[] = $arr[$value];
                }
                $spe_price_id   = implode('-',$spe_id);

                $ins['uniacid'] = $this->_uniacid;

                $ins['goods_id']= $good_id;

                $ins['spe_id_1']= $spe_price_id;

                $ins['price']   = $v['price'];

                $ins['stock']   = $v['stock'];

//                $ins['alert_stock']   = $v['alert_stock'];

                $ins['status']  = 1;
                //原价
                $ins['original_price'] = !empty($v['original_price'])?$v['original_price']:0;
                //成本价
                $ins['cost_price'] = !empty($v['cost_price'])?$v['cost_price']:0;

                $spe_price = $this->spe_price_model->singeSpePrice(['goods_id'=>$good_id,'spe_id_1'=>$spe_price_id,'uniacid'=>$this->_uniacid]);

                if(empty($spe_price)) {

                    $res = $this->spe_price_model->goodsSpePriceAdd($ins);

                }else{

                    $res = $this->spe_price_model->goodsSpePriceUpdate(['id'=>$spe_price['id']],$ins);
                }
            }
        }
        return !empty($res)?$res:1;
    }









}
